--
-- @Author:      feilong
-- @DateTime:    2019-11-13 23:05:48
-- @Description: 消息的处理
local skynet = require("skynet")
local redis = require("skynet.db.redis")
local skynet_queue = require("skynet.queue")
local server_config = dofile(skynet.getenv("server_config"))

local table_remove = table.remove
local table_insert = table.insert


local MessageHandler = class("MessageHandler")


---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch)
	self.message_dispatch = message_dispatch
	self.skynet_queue_fun = {}
	local db_conf = server_config.redis_conf	
	self.host = db_conf.host
	self.port = db_conf.port
	self.auth = db_conf.auth
	self.db_id = db_conf.db or 13	
	if self.auth == "" then 
		self.auth = nil
	end
	self.db_info = {
		host = self.host,
		port = self.port,
		db = self.db_id,
		auth = self.auth,
	}
	dbglog("__redis_db_info____", dump(self.db_info))
	self.connections = {} --连接池
	self.allocated_connection_num = 0
	self.max_connection_num = 100 

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()
	self.message_dispatch:registerSelf("start", handler(self,self.start))
	self.message_dispatch:registerSelf("redis_cmd", handler(self,self.redisCommand))
	self.message_dispatch:registerSelf("normal_cmd", handler(self,self.normalCommand))
	self.message_dispatch:registerSelf("sync_cmd", handler(self,self.syncCommand))
end

--从连接池里取一个服务
function MessageHandler:getConnect()

    local connections = self.connections
    if #connections > 0 then
        return table_remove(connections)
    end
    while self.allocated_connection_num >= self.max_connection_num do
        --超上限了，唯有空转等了
        errlog('there is no connection for reusing, waiting for one reused connection')
        skynet.sleep(5)
        if #connections > 0 then
            return table_remove(connections)
        end
    end

    local ok,ret = xpcall(redis.connect, debug.traceback, self.db_info)
    while not ok do
        errlog('failed to connect redis',ret)
        skynet.sleep(100)   --one second
        ok,ret = xpcall(redis.connect, debug.traceback, self.db_info)
    end

    self.allocated_connection_num = self.allocated_connection_num + 1
    return ret
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------

function MessageHandler:start()
	print("______redis_start_______")
	return true
end

function MessageHandler:normalCommand(cmd, ...)
	-- body	
	local conn = self:getConnect()
	local func = conn[cmd]
    local ok,ret = xpcall(func, debug.traceback, conn, ...)
    while not ok do
        errlog("___发送消息给redis错误___", ret)
        skynet.sleep(100)
        print('redis now retry....')
        ok,ret = xpcall(func, debug.traceback, conn, ...)
    end
    --把连接放回池中
	table_insert(self.connections, conn)
    if not ok then
		errlog(ret) 
	end
	return ret
end

--redis命令处理
function MessageHandler:redisCommand(sync_id, cmd, ...)
	if sync_id then
		return self:syncCommand(sync_id, cmd, ...)
	end
	return self:normalCommand(cmd, ...)
end

--根据sync_id同步处理
function MessageHandler:syncCommand(sync_id, cmd, ...)
	if not sync_id then
		errlog("___发送消息给redis错误___assigin_id is not__")
		return 
	end
	--按指定id同步执行
	local fun = self.skynet_queue_fun[sync_id]
	if not fun then 
		fun = skynet_queue()
		self.skynet_queue_fun[sync_id] = fun
	end
	local function call_redis(cmd, ...)
		return self:normalCommand(cmd, ...)
	end
	return fun(call_redis, cmd, ...)
end



return MessageHandler